<template>
	<view class="rnt">
		<scroll-view scroll-y="true" class="scrollView" :scroll-into-view="bottomId">
			<view style="height: 100rpx;"></view>
			<view class="example_box">
				<view class="example_titie">
					<image src="/static/peo/pp.png" mode=""></image>
					<text style="font-size: 27rpx;margin-left: 20rpx;">你好，你现在需要我做些什么呢?快来提问或者和我聊天吧!</text>
				</view>
				<view class="example" v-for="(item,index) in example" :key="index" @click="getExample(item)">
					<text style="margin-left: 20px;">{{item.question}}</text>
				</view>
			</view>
			<!-- 用来获取消息体高度 -->
			<view id="okk">
				<!-- 消息 -->
				<view class="flex-column-start" v-for="(x,i) in msgList" :key="i">

					<!-- 机器人消息 -->
					<view v-if="!x.my" class="aiinfo">
						<view class="chat-imgs ">
							<image src="../../static/peo/QS.png" mode=""></image>
						</view>
						<view class="flex"
							style="min-width: 200rpx; max-width: 500rpx;position: relative;background:#ffffff;padding-top: 20rpx;color: white;padding-bottom: 20rpx;border-radius: 30rpx;margin-left: 80rpx;padding-right: 15px;">
							<view class="aimsg left">
								<zero-loading v-if="x.title==true" type="pulse" position="absolute"></zero-loading>
								<view class="textAi" v-if="x.msg != true" @click="copy(x.msg)">
									<u-tooltip color="#ffffff" :direction="i==0?' bottom':'top'" :text="x.msg"
										:buttons="['删除']" @click='tooltip($event,i)'>
									</u-tooltip>
								</view>
								<view v-if="x.msg=='当前咨询人数过多，请重试...'">
								</view>
							</view>
							<!-- <view class="copys" v-if="x.msg" @click="copy(x.msg)">
								<image src="../../static/11.png" mode=""></image>
								<view class="copy-s">
									复制
								</view>
							</view> -->
						</view>

					</view>
					<!-- 用户消息 头像可选加入-->
					<view v-if="x.my" class="userInfo">
						<view class="chat-img ">
							<image src="../../static/peo/s.png" mode=""></image>
						</view>
						<view class="flex" style="max-width: 600rpx;position:absolute;right:130rpx;">
							<view class="aimsg right">
								<view class="textUser" @click="copy(x.msg)">
									<u-tooltip :direction="i==0?' bottom':'top'" :text="x.msg" :buttons="['删除']"
										@click='tooltip($event,i)'>
									</u-tooltip>
								</view>
							</view>
							<!-- <view class="copy">
								<image src="../../static/11.png" mode=""></image>
								<view class="copy-s">
									复制
								</view>
							</view> -->
						</view>

					</view>
				</view>
			</view>
			<view class="" :id="'p'+(msgList.length - 1>0? (msgList[msgList.length - 1].msg.length):'')">
			</view>
		</scroll-view>
		<!-- 底部导航栏 -->
		<view class="flex-column-center">
			<view class="inpubut" v-if="msgLoad == false">
				<view class="dh-input">
					<textarea v-model="msg" maxlength="-1" placeholder="想和我聊点什么?" auto-height fixed
						confirm-type="search" placeholder-class="my-neirong-sm" class="input" @confirm="sendMsg">
					</textarea>

				</view>
				<view class="footer">
					<image src="../../static/peo/cp.png" style="width: 72rpx;height: 72rpx;" @click="sendMsg"></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import * as TextEncoding from 'text-encoding-shim';
	import cryptoJs from '@/utils/encryptDES.js';
	import {
		apiMixUrlApi
	} from "../../api/assemb";
import row from '../../uni_modules/uview-ui/libs/config/props/row';

	function hasDuplicateSubstring(str, substring) {
		const regex = new RegExp(substring, 'g'); // 创建一个全局搜索的正则表达式  
		const matches = str.match(regex); // 使用match方法查找所有匹配项  
		return matches && matches.length > 1; // 如果有匹配项且数量大于1，则返回true，否则返回false  
	}
	export default {
		data() {
			return {
				baseInfo: '',
				content: [],
				teststr: '',
				apiurl: '', //后台地址以及后台部署教程插件小程序回复客服获取
				apisucc: false,
				msgLoad: false,
				msgList: [{
					msg: '你有什么要问的嘛',
					my: true,
				}],
				msg: "",
				xinxi_g: "",
				isVip: true,
				showExample: true,
				OS: '',
				frequency: uni.getStorageSync('frequency'),
				example: [{
						question: '请给我一份上海的旅游攻略'
					},
					{
						question: '写一篇关于秋天的文章'
					}, {
						question: '外星人真的存在吗？'
					}
				],
				bottomId: '',
				listTile: [],
				fistTitle: 0,
				footerTitle: 0,
				time: '',
				isPause: false,
				aa: '',
				typingQueue: [],
				isTyping: false,
			}
		},
		onLoad(option) {
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
			this.msgList = uni.getStorageSync('msgList') || []
			this.msgList = this.msgList.filter(item => {
				return item.msg != true
				console.log(item);
			})

			// if (option.content) {
			// 	this.msgList.push({
			// 		"msg": option.content,
			// 		"my": false,
			// 	})
			// } else {
			this.msgList.push({
				"msg": '我是你的智能秘书，有什么不会的你可以问我',
				"my": false,
			})
			// }
		},
		onShow() {
			setTimeout(() => {
				this.bottomId = 'p' + (this.msgList.length - 1 > 0 ? (this.msgList[this.msgList.length - 1].msg
					.length) : '')
			}, 0)
			if (this.msgList.length > 0) {
				this.showExample = false
			}

		},
		methods: {
			async processTypingQueue() {
				let that = this
				if (that.typingQueue.length > 0) {
					that.isTyping = true; // 标记为正在进行打字机效果  
					const dataToProcess = that.typingQueue.shift(); // 获取队列中的第一个数据块并移除它  
					await that.typeWriterEffect(dataToProcess); // 执行打字机效果，并等待它完成  
					that.isTyping = false; // 标记为打字机效果已完成  
					// 递归调用以处理队列中的下一个数据块（如果有的话）  
					if (that.typingQueue.length > 0) {
						that.processTypingQueue();
					}
				}
			},

			// 打字机效果函数，使用async/await确保按顺序执行  
			async typeWriterEffect(text) {
				let that = this
				for (let i = 0; i < text.length; i++) {
					that.msgList[that.msgList.length - 1].msg += text[i];
					setTimeout(() => {
						that.bottomId = 'p' + (that.msgList[that.msgList.length - 1].msg
							.length)
					}, 0)
					await new Promise(resolve => setTimeout(resolve, 30)); // 200ms延迟  
				}
			},

			tooltip(e, i) {
				event.stopPropagation()
				console.log(e, i);
				if (e != 0) {
					this.msgList.splice(i, 1)
				}
				uni.setStorageSync('msgList', this.msgList)
			},
			getExample(e) {
				console.log(e);
				this.msg = e.question
				this.sendMsg()
			},
			del(i) {
				this.msgList.splice(i, 1)
				uni.setStorageSync('msgList', this.msgList)
			},
			copy(e) {
				uni.setClipboardData({
					data: e,
					showToast: false,
					success: function() {
						uni.showToast({
							title: '复制成功',
							icon: 'none',
							duration: 2000
						})
					}
				});
			},
			async sendMsg() {
				const that = this
				if (that.msg == "") {
					uni.showToast({
						title:'请输入内容',
						icon:'none'
						})
					return
				}
				if(uni.getStorageSync('frequency') > 0 || this.isVip){
					that.msgList.push({
						"msg": that.msg,
						"my": true,
					})
					setTimeout(() => {
						that.bottomId = 'p' + (that.msgList[that.msgList.length - 1].msg
							.length)
					}, 0)
					if (that.msgList[that.msgList.length - 1].msg !== true) {
						that.msgList.push({
							"msg": '',
							"my": false,
							"title": true
						})
					}
					that.msgLoad = true
					const requestTask = wx.request({
						url: 'https://ser.aixiezuo888.com/chat/api/c=1012&v=4&a=wxzy', // 服务端接口地址
						data: cryptoJs.encrypt(JSON.stringify({
							cmd: "bdStream",
							base: wx.getStorageSync("baseinfo"),
							param: {
								content: that.msg
							},
						}), 1012),
						method: 'POST',
						enableChunked: true,
						header: {
							//'content-type': 'application/x-www-form-urlencoded',
							Accept: 'text/event-stream'
						},
						success: (response) => {
							console.log(response, 'res')
							if (response.statusCode == 200 || uni.getStorageSync('OS') == 'windows') {
								setTimeout(() => {
									that.msgLoad = false
								}, 3200)
								// that.feacter()
							} else {
								this.creativeResults = ''
								uni.showToast({
									title: '出错了请重试',
									icon: 'none',
									duration: 2000
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 2000);
							}
						}
					});
					requestTask.onChunkReceived((chunk) => {
						const arrayBuffer = chunk.data;
						const uint8Array = new Uint8Array(arrayBuffer);
						const str = new TextEncoding.TextDecoder('utf-8').decode(uint8Array);
						that.pos = str.replace(/data:/g, '');
						if (hasDuplicateSubstring(that.pos, 'data')) {
							const pt = that.pos.replace(/\r?\n/g, '')
							const pos = pt.replace(/"code":200,"message":"SUCCESS","data":/g, '');
							const ps = pos.replace(/[{}""]/g, '') + '"}';
							const rs = '{"code":200,"message":"SUCCESS","data":"'
							that.pos = rs + ps
						}
						const po = JSON.parse(that.pos)
						console.log(po, '111')
						if (po.code == 200) {
							uni.hideLoading()
							that.msgList[that.msgList.length - 1].title = false
							that.typingQueue.push(po.data);
							// 如果当前没有打字机效果在进行，则开始处理队列  
							if (!that.isTyping) {
								that.processTypingQueue();
							}
						} else {
							this.creativeResults = ''
							uni.showToast({
								title: po.message,
								icon: 'none',
								duration: 2000
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 2000);
						}
					});
				}else{
					uni.showToast({
						title:'您还不是会员',
						icon:'none'
					})
				}
			}
		}
	}
</script>

<style lang="less">
	.rnt {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-image: url('https://iflytts.oss-cn-qingdao.aliyuncs.com/website/img/webway/long.png');
		background: #ECF2FF;

	}

	/deep/.u-tooltip__wrapper__popup__list__btn {
		&--hover {
			background-color: #5eb5a2;
		}
	}

	/deep/.u-tooltip__wrapper__text {
		font-size: 29rpx;
		width: 100%;
		color: #ffffff;
		font-size: 24rpx;
		display: inline-block;
		white-space: pre-wrap;
		height: auto;
	}


	/deep/.u-tooltip__wrapper__popup__indicator {
		background: linear-gradient(93deg, #5A8CEE 0%, #4D83F0 51%, #4374DE 100%);
	}

	/deep/.u-tooltip__wrapper__popup__list {
		background: linear-gradient(93deg, #5A8CEE 0%, #4D83F0 51%, #4374DE 100%);
	}

	/deep/.uni-textarea-wrapper {
		// background-color: #ffffff;
	}

	/deep/uni-textarea {
		min-height: 40rpx;
	}

	.aiinfo/deep/.u-tooltip__wrapper__text {
		color: #333333;
		font-size: 24rpx;
	}

	.flex-column-start {
		// border-bottom: 1rpx solid #999999;
	}

	uni-button {
		padding: 0;
		background-color: #fff;
	}

	.button-hover {
		background-color: #fff;
	}

	// uni-button:after {
	// 	border: none;
	// }

	page {
		background-color: #fff;
	}

	.example_box {
		position: relative;
		width: 694.44rpx;
		height: 470rpx;
		margin: auto;
		// margin-top: 100rpx;
		margin-bottom: 20rpx;
		padding: 0rpx 45rpx 10rpx 39rpx;
		background-color: white;
		border-radius: 18rpx;
		box-sizing: border-box;

		.example_top {
			display: flex;
			align-items: center;
			position: absolute;
			top: -70rpx;
			left: 10rpx;
			width: 479rpx;
			height: 103rpx;
			background: #4BB591;
			border-radius: 18rpx;

			image {
				margin-left: 27rpx;
				margin-right: 18rpx;
				width: 72.46rpx;
				height: 72.46rpx;
			}

			text {
				width: 270rpx;
				font-size: 25rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #666666;
			}
		}

		.example_titie {
			display: flex;
			align-items: center;
			height: 140rpx;

			image {
				width: 80.46rpx;
				height: 62.46rpx;
				margin-right: 10rpx;
			}

			text {
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #666666;
				line-height: 45rpx;
			}
		}

		.example {
			margin-top: 20rpx;
			background-repeat: no-repeat;
			background-size: cover;
			background-image: url("https://iflytts.oss-cn-qingdao.aliyuncs.com/website/img/webway/wide.png");
			display: flex;
			justify-content: space-between;
			align-items: center;
			// border-bottom: 1px solid #CFCFCF;

			&:last-child {
				border-bottom: none;
			}

			text {
				font-size: 25rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #666666;
				line-height: 78rpx;
			}

			image {
				width: 30.19rpx;
				height: 23.55rpx;
			}
		}
	}

	.scrollView {
		width: 100%;
		height: 90vh;
	}

	.textAi {
		word-break: break-all;
		font-size: 29rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		line-height: 51rpx;
	}

	.textUser {
		word-break: break-all;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		line-height: 51rpx;
		background: linear-gradient(93deg, #5A8CEE 0%, #4D83F0 51%, #4374DE 100%);
		padding-top: 10rpx;
		padding-bottom: 10rpx;
		color: white;
		padding-left: 20rpx;
		border-radius: 16rpx;
		padding-right: 20rpx;
	}

	// .copy_box {
	// 	display: flex;
	// 	flex-direction: row-reverse;
	// 	margin-top: 10rpx;
	// 	// bottom: 0px;

	// 	.copy_box_img {
	// 		width: 36.23rpx;
	// 		height: 36.23rpx;
	// 		margin-right: 31.4rpx;
	// 	}
	// }

	.banner_txt {
		position: absolute;
		top: 33.21rpx;
		left: 132.85rpx;
		width: 571rpx;
		height: 68rpx;
		font-size: 27rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #666666;
		line-height: 40rpx;
	}

	// .banner_box {
	// 	position: fixed;
	// 	left: 0;
	// 	top: 0;
	// 	width: 750rpx;
	// 	height: 152.78rpx;
	// 	background-image: url('../../static/banner.png');
	// 	background-size: cover;
	// 	z-index: 999;
	// }

	.userInfo {
		display: flex;
		flex-direction: row;
		padding-left: 36rpx;
		padding-top: 38rpx;
		padding-bottom: 42rpx;
		animation: oneshow 0.8s ease 1;
		margin-top: 50rpx;
		position: relative;
	}

	// .usermsg {
	// 	margin-left: 20rpx;
	// 	padding: 17rpx 20rpx;
	// 	border-radius: 35rpx;
	// }

	.aiinfo {
		display: flex;
		flex-direction: row;
		padding-left: 36rpx;
		padding-top: 38rpx;
		padding-bottom: 42rpx;
		animation: oneshow 0.8s ease 1;
		position: relative;
		margin-top: 50rpx;
	}

	.copy {
		position: absolute;
		top: 10rpx;
		left: -30rpx;

		.copy-s {
			width: 50rpx;
			font-size: 19rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #767676;
		}

		image {
			height: 39rpx;
			width: 39rpx;
		}

	}

	.copys {
		position: absolute;
		top: 10rpx;
		right: -70rpx;

		.copy-s {
			width: 50rpx;
			font-size: 19rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #767676;
		}

		image {
			height: 39rpx;
			width: 39rpx;
		}

	}

	.chat-img {
		border-radius: 50%;
		width: 61rpx;
		height: 61rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		left: 640rpx;
		position: absolute;

		image {
			width: 100%;
			height: 100%;

		}
	}

	.chat-imgs {
		border-radius: 50%;
		width: 61rpx;
		height: 61rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		position: absolute;
		left: 40rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.aimsg {
		display: flex;
		flex-direction: column;
		justify-content: center;
		margin-left: 24rpx;
		border-radius: 14rpx;
	}

	.flex-column-center {
		background: #ECF2FF;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: fixed;
		bottom: 0rpx;
		width: 100%;
		min-height: 10vh;

		// background:#E6F3FD;
		// border-top: 1rpx solid #BFBFBF;
	}

	.inpubut {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #ECF2FF;
		width: 100%;
		min-height: 10vh;
		font-size: 40rpx;
		padding: 30rpx 0;
		box-sizing: border-box;


	}

	.footer {
		width: 97rpx;
		height: 69rpx;
		background: #E9EDFB;
		border-radius: 34rpx;
		align-items: center;
		justify-content: space-around;
		display: flex;
		margin-left: 20rpx;
	}

	.dh-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 75%;
		min-height: 80rpx;
		color: #333;
		background-color: #fff;
		padding: 15rpx;
		box-sizing: border-box;
		border-radius: 40rpx;
		margin-left: 30rpx;

		.input {
			background-color: #fff;
			box-sizing: border-box;
			font-size: 25rpx;
		}

		image {
			width: 32rpx;
			height: 32rpx;
			margin-right: 40rpx;
		}
	}

	.my-neirong-sm {
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
	}

	.btn {
		height: 90rpx;
		width: 35%;
		background-color: cornflowerblue;
		color: #666666;
		border-radius: 2500px;

	}

	.popcls {
		width: 80vw;
		height: 40vh;
		background: white;
		border-radius: 20rpx;
		display: flex;
		flex-direction: column;
		justify-items: center;
		align-items: center;
	}

	.setBtn {
		width: 68.24rpx;
		height: 68.84rpx;
		position: relative;

		.setBtnImg {
			width: 68.24rpx;
			height: 68.84rpx;
		}
	}

	.share-btn {
		/* 		width: 0;
		height: 0; */
		background-color: #111827;
		position: relative;
		opacity: 0.8;
		margin: 0;
	}

	.mine {
		width: 350rpx;
		height: 100vh;
		background-color: #fff;
	}
</style>